<template>
  <view class="gameMain-page">
		<!-- 游戏部分 -->
		<view class="game-content">
			<view class="btns">
				<button class="btn-share" open-type="share" @click="goShare"></button>
				<image class="btn-gift" src="/static/common/image/btn-gift.png" mode="widthFix" @click="goNextPage(2)"></image>
				<image class="btn-rule" src="/static/common/image/btn-rule.png" mode="widthFix" @click="goNextPage(1)"></image>
			</view>
			<!-- 窗口 -->
			<view class="game-box">
				<image class="mask" src="/static/common/image/mask.png" mode="widthFix"></image>
				<!-- 掉落礼物 -->
				<view class="gifts">
					<block v-for="(item,index) in hongbaoArr" :key="index">
						<image
							:style="{'width':item.width, 'animation-duration': item.duration + 's','left': item.left, 'display': item.display}"
							class="hongbao"
							mode="widthFix"
							:src="item.bg1"
							@click="clickHandler(item,index)"
						></image>
					</block>
				</view>
				<!-- 进场 -->
				<view v-if="gameStartFlag">
					<image class="timer-count" :src="gameOverFlag ? 'https://cdc-file.risechina.com/img/2022/1/1641626380037.png': 'https://cdc-file.risechina.com/img/2022/1/1641610047920.png'" mode="widthFix"></image>
				</view>
				<!-- 分数时间 -->
				<view class="game-bottom">
					<view class="score">
						<image class="icon" src="https://cdc-file.risechina.com/img/2022/1/1641608484539.png" mode="widthFix"></image>
						<view class="text">+{{pad(score,3)}}</view>
					</view>
					<view class="timer">
						<image class="icon" :src="countTimer < 30 && countTimer > 0 ? 'https://cdc-file.risechina.com/img/2022/1/1641608657538.png' : '/static/common/image/shao.png'" mode="widthFix"></image>
						<view class="text">00:{{pad(countTimer,2)}}</view>
					</view>
				</view>
				<!-- 豹子 -->
				<view>
					<image class="baozi" src="https://mmbiz.qpic.cn/mmbiz_gif/snDtyORuY5sEKy1rqFLvZkDorxD3a6QtxNXSuOyBCgDicAUjVzV8khiayfsYNnOlv0WVEZpqNZ2mEVCHcEicAMFEw/0?wx_fmt=gif" :animation="baoziAni" mode="widthFix"></image>
				</view>
			</view>
		</view>
		<!-- 中奖部分 -->
		<view class="gift-content">
			<!-- 头等奖 -->
			<view v-if="prizeType === 99" class="gift1 gift">
				<image class="bg" src="/static/common/image/gift1bg.png" mode="widthFix"></image>
				<image class="gift-pic" src="https://cdc-file.risechina.com/img/2022/1/1641875807423.png" mode="widthFix"></image>
				<image class="btn-to-get" src="/static/common/image/btn-to-get.png" mode="widthFix" @click="prizeType = 88"></image>
				<image class="btn-to-gift" src="/static/common/image/btn-to-gift.png" mode="widthFix" @click="goNextPage(2)"></image>
			</view>
			<!-- 表情 -->
			<view v-if="prizeType === 0" class="gift2 gift">
				<image class="bg" :src="score > 100 ? '/static/common/image/nogift2.png' : '/static/common/image/nogift.png'" mode="widthFix"></image>
				<image class="gif-emjoy" :src="prizeUrl" mode="widthFix" @longtap="savePoster(prizeUrl)">
				<image class="btn-again" src="/static/common/image/btn-again.png" mode="widthFix" @click="goNextPage(1)"></image>
			</view>
			<!-- 优惠券 -->
			<view v-if="prizeType === 1" class="gift3 gift">
				<image class="bg" src="/static/common/image/youhiuquan.png" mode="widthFix"></image>
				<image class="youhuiquan" :src="prizeUrl == 1 ? '/static/common/image/gift-100.png' : prizeUrl == 2 ? '/static/common/image/gift-188.png' : '/static/common/image/gift-888.png'" mode="widthFix"></image>
				<image class="btn-again" src="/static/common/image/btn-again.png" mode="widthFix" @click="goNextPage(1)"></image>
				<image class="btn-to-gift" src="/static/common/image/btn-to-gift.png" mode="widthFix" @click="goNextPage(2)"></image>
			</view>
			<!-- 填写地址 -->
			<view v-if="prizeType === 88" class="gift4 gift">
				<image class="bg" src="/static/common/image/bgaddress.png" mode="widthFix"></image>
				<image class="btn-again" src="/static/common/image/btn-to-get.png" mode="widthFix" @click="addressSave"></image>
				<view class="user-info">
					<u-field
						class="form-name form-username"
						v-model="formData.name"
						label-width="0"
						maxlength="10"
						:clearable="false"
						:border-bottom="false"
					>
					</u-field>
					<u-field
						class="form-name form-mobile"
						v-model="formData.mobile"
						style="margin-top:100rpx"
						label-width="0"
						maxlength="20"
						:clearable="false"
						:border-bottom="false"
					>
					</u-field>
					<u-field
						class="form-name form-address"
						v-model="formData.address"
						label-width="0"
						maxlength="22"
						type="textarea"
						:clearable="false"
						:border-bottom="false"
						:auto-height="false"
					>
					</u-field>
				</view>
			</view>
			<!-- 授权手机号 -->
			<view v-if="needSQ" class="mobile-sq gift">
				<image class="bg" src="/static/common/image/sqbg.png" mode="widthFix"></image>
				<view class="txt">{{mobile}}</view>
				<button
          class="mobile"
          open-type="getPhoneNumber"
          @getphonenumber="bindgetphonenumber"
        >	
        </button>
				<view class="confirm-btn" @click="confirmSQ"></view>
			</view>
			<view v-if="needSH" class="share-bg gift">
				<image class="bg" src="/static/common/image/bgShare.png" mode="widthFix"></image>
				<button class="btn-share2" open-type="share" @click="goShare"></button>
				<image class="btn-to-gift" src="/static/common/image/btn-to-gift.png" mode="widthFix" @click="goNextPage(2)"></image>
			</view>
		</view>
  </view>
</template>


<script>
import userMixins from "@/mixins/userMixins";
import { iconMap } from './iconMap'
export default {
  data() {
    return {
			hongbaoArr: [],
			baoziAni: {},
			score: 0,
			countTimer: 15,
			gameStartFlag: false,
			gameOverFlag: false,
			prizeType: null,
			prizeUrl: '',
			formData: {
				name: '',
        address: '',
        mobile: ''
			},
			mobile: '',
			needSQ: false,
			needSH: false,
			bigGift: 0
    };
  },
  mixins: [userMixins],
  onLoad(options) {
		this.preloadAni()
		if (this.vuex_userInfo.mobile) {
			this.checkUserByWechatApp().then(this.init)
		} else {
			this.needSQ = true;
		}
  },
  methods: {
		preloadAni() {
			// 豹子动画
			this.animation = wx.createAnimation({
				duration: 1000,
				timingFunction: 'ease',
				delay: 0
			});
		},
    init() {
      console.log('init')
      if (this.vuex_userInfo.game_num > 0) {
        this.canPlay = true
      } else {
        this.canPlay = false
				if (this.vuex_userInfo.day_share > 2) {
					uni.showToast({
						title: '转发已达上限',
						duration: 10000,
						icon: 'error'
					});
				} else {
					this.needSH = true;
				}
      }
			if(!this.canPlay) return;
			this.gameStartFlag = true;
			setTimeout(_=>{
				this.timeCount();
				this.gameStart();
			},6000)
    },
    goNextPage(type) {
			let url = ''
			switch (type) {
				case 1:
					url = '/pages/loading/index?flag=1';
					break;
				case 2:
					url = '/pages/giftCenter/index';
					break;
			}
      uni.navigateTo({ url });
    },
		// 中奖
		async gameOver() {
			this.gameOverFlag = true;
			console.log('gameover')
			let res = await this.$u.api.TASAKIBOOKAPI.choujiang({
				openid: this.vuex_wechatInfo.openId,
				score: this.score
			})
      console.log(res,'抽奖结果')
			// ---
			// res = {
			// 	status: 200,
			// 	data: {
			// 			win: 0,
			// 			prize: {
			// 				type: 0,
			// 				url: 'https://cdc-file.risechina.com/img/2022/1/1641280861718.png'
			// 			}
			// 	}
			// }
			// --
      if (res.status === 200) {
				//中礼盒
				if (res.data.win) {
					// 豹子移动
					setTimeout(_=>{
						this.animation.translateY('-360rpx').step();
						this.baoziAni = this.animation.export()
						setTimeout(_=>{
							this.prizeType = 99
						},1000)
					},1000)
				} else if (res.data.prize.type === 1 ) {
					// 优惠券
					let prize = res.data.prize;
					// 豹子移动
					setTimeout(_=>{
						this.animation.translateY(`-${90 * prize.url}rpx`).step();
						this.baoziAni = this.animation.export()
						setTimeout(_=>{
							this.prizeType = prize.type;
							this.prizeUrl = prize.url
						},1000)
					},1000)	
				} else {
					let prize = res.data.prize;
					// 表情
					this.prizeType = prize.type;
					this.prizeUrl = prize.url
				}
      } else {
        uni.showToast({
          title: res.msg,
          duration: 2000,
          icon: 'error'
        });
      }
		},
    async addressSave() {
      let errorMsg;
			if (!this.formData.name) {
				errorMsg = '请填写姓名'
			} else if (!this.formData.mobile) {
				errorMsg = '请填写手机号'
      } else if(!this.formData.address) {
        errorMsg = '请填写地址'
      } else if (!/^1\d{10}$/.test(this.formData.mobile)) {
        errorMsg = '请填写正确手机号'
      }
			if (errorMsg) {
				uni.showToast({
					title: errorMsg,
					duration: 3000,
					icon: 'none'
				});
			} else {
				let res = await this.$u.api.TASAKIBOOKAPI.setAddress({
          openid: this.vuex_wechatInfo.openId,
					...this.formData
        })
				if(res.status === 200) {
					this.$u.vuex("vuex_userInfo.sj_address", this.formData.address);
					this.$u.vuex("vuex_userInfo.sj_mobile", this.formData.mobile);
					this.$u.vuex("vuex_userInfo.sj_name", this.formData.name);
					uni.showToast({
						title: '申领成功',
						duration: 2000,
						icon: 'success'
					});
					this.prizeType = -1
				}
			}
    },
    // setInfo() {
    //   this.addressShow = true;
    //   this.formData.name = this.vuex_userInfo.sj_name || ''
    //   this.formData.address = this.vuex_userInfo.sj_address || ''
    //   this.formData.mobile = this.vuex_userInfo.sj_mobile || ''
    // },
		randomNum(minNum,maxNum) {
			return parseInt(Math.random()*(maxNum-minNum+1)+minNum,10); 
		},
		randomGift(minNum,maxNum) {
			let random = parseInt(Math.random()*(maxNum-minNum+1)+minNum,10)
			if(random >= 13) {
				this.bigGift ++
			}
			if (this.bigGift > 3) {
				return parseInt(Math.random()*13,10); 
			} else {
				return random
			}
		},
		gameStart() {
			let random = this.randomGift(0,16)
			let gift = iconMap[random];

			let clone = JSON.parse(JSON.stringify(gift)) 
			clone.left = this.randomNum(100,505) + 'rpx';
			clone.duration = this.randomNum(3,4)
			this.hongbaoArr.push(clone);

			if(this.countTimer > 0){
				setTimeout( _=> {
					this.gameStart()
				}, this.countTimer > 10 ? 600 : 500) 
			} else {
				this.gameOver()
			}
		},
		timeCount() {
			let time = setInterval( _=> {
				if (this.countTimer > 0) {
					this.countTimer --
				}
			}, 1000);
		},
		clickHandler(item,index) {
			if(this.gameOverFlag) return;
			item.bg1 = item.bg2;
			this.score += item.score;
			setTimeout(_=>{
				item.display = 'none'
			},600)
		},
		pad(num, len) {
			if(num < 0) {
				this.score = 0;
				return '000'
			} else {
				if(String(num).length > len) return num;
    		return (Array(len).join(0) + num).slice(-len);
			}
		},
		savePoster(url) {
			wx.showLoading({
        title: '保存图片中',
      })
      let fileName = new Date().valueOf();
			let that = this;
			wx.downloadFile({
				url,
        filePath: wx.env.USER_DATA_PATH + '/' + fileName + '.jpg',
				success(res) {
          console.log(res, 'downloadFile res')
					if (res.statusCode === 200) {
            console.log(res.tempFilePath,'tempFilePath')
						wx.saveImageToPhotosAlbum({
							filePath: res.filePath,
							success () {
								wx.hideLoading();
								uni.showToast({
									title: '保存相册成功',
									duration: 3000,
									icon: 'success'
								});
							},
							fail() {
								wx.hideLoading();
								that.getPermission()
							}
						})
					} else {
						wx.hideLoading();
						uni.showToast({
							title: '下载图片失败',
							duration: 3000,
							icon: 'error'
						});
					}
				},
				fail() {
					reject(new Error(`downloadFile:fail ${img}`))
				}
			})
		},
		// 获取手机号秘钥
		async bindgetphonenumber(e) {
			console.log("获取手机号",e)
      if (typeof e.mp.detail.encryptedData !== 'string') {
        return
      }
      // 获取手机号后
      let that = this;
      let res = await that.$u.api.WXCHATAPI.getWXMobile({
        sessionKey: that.vuex_wechatInfo.sessionKey,
        encryptedData: e.mp.detail.encryptedData,
        iv: e.mp.detail.iv
      })
      this.mobile = res.data.phoneNumber
		},
		// 登陆
		async confirmSQ() {
			let errorMsg;
			if (!this.mobile) {
				errorMsg = '请填写手机号'
			}
			if (errorMsg) {
				uni.showToast({
					title: errorMsg,
					duration: 3000,
					icon: 'none'
				});
			} else {
				let res = await this.$u.api.TASAKIBOOKAPI.setInfo({
          openid: this.vuex_wechatInfo.openId,
					mobile: this.mobile
        })
				if(res.status === 200) {
					uni.showToast({
						title: '登陆成功',
						duration: 2000,
						icon: 'success'
					});
					this.needSQ = false;
					this.checkUserByWechatApp().then(this.init);
				}
			}
		},
		// 打开权限面板
    getPermission() {
			wx.showModal({
				title: '提示', //提示的标题,
				content: '为了保存表情图片，请打开【添加到相册】权限', //提示的内容,
				showCancel: true, //是否显示取消按钮,
				cancelText: '取消', //取消按钮的文字，默认为取消，最多 4 个字符,
				success: res => {
					if (res.confirm) {
						// openSetting 是需要事件驱动的，保证它的同步性。
						wx.openSetting({
							success(res) {
								console.log('打开了')
							},
							fail(res) {
							}
						})
					}
				}
			});
    },
		goShare() {
			if (this.vuex_userInfo.game_num === 0 && this.vuex_userInfo.day_share < 2) {
				setTimeout(_=>{
					uni.navigateTo({ url: '/pages/loading/index?flag=1' });
				},2000)
			}
		}
  }
};
</script>

<style lang="scss" scoped>
.gameMain-page {
  width: 100vw;
  height: 100vh;
	position: fixed;
	display: flex;
	justify-content: center;
	align-items: center;
	background-color: #f4313f;
	.logo {
		width: 300rpx;
		position: absolute;
		top: 176rpx;
		left: 215rpx;
		z-index: 222;
	}
	.game-content {
		position: relative;
		width: 750rpx;
		height: 1650rpx;
		background: url('/static/common/image/bgGame.png') no-repeat center center;
		background-size: 100% 100%;
		.btns {
			position: absolute;
			right: 20rpx;
			top: 200rpx;
			display: flex;
			flex-flow: column;
			justify-content: center;
			align-items: center;
			z-index: 1111;
			.btn-share {
				width: 69rpx;
				height: 73rpx;
				background-color: transparent;
				border-radius: 0;
				background: url('/static/common/image/btn-share.png') no-repeat center center;
				background-size: 100%;
				&::after {
					border: none;
				}
			}
			.btn-gift {
				margin-top: 21rpx;
				width: 69rpx;
			}
			.btn-rule {
				margin-top: 21rpx;
				width: 69rpx;
			}
		}
		.game-box {
			.mask {
				width: 750rpx;
				height: 100rpx;
				position: absolute;
				top: 80rpx;
				left: 0;
				z-index: 111;
				pointer-events: none;
			}
			.hongbao {
				// width: 100rpx;
				position: absolute;
				top: 80rpx;
				animation: dropDown 1.5s linear 1 both;
				border: 15rpx solid transparent;
    		background-clip: padding-box;
			}
			.game-bottom {
				width: 340rpx;
				position: absolute;
				bottom: 190rpx;
				left: 220rpx;
				display: flex;
				justify-content: space-between;
				align-items: center;
				.score {
					display: flex;
					justify-content: center;
					align-items: center;
					flex-flow: column;
					.icon {
						width: 60rpx;
					}
					.text {
						margin-top: 19rpx;
						font-size: 36rpx;
						color: #d4bf97;
						font-weight: 500;
					}
				}
				.timer {
					width: 86rpx;
					display: flex;
					justify-content: center;
					align-items: center;
					flex-flow: column;
					.icon {
						width: 80rpx;
					}
					.icon2 {
						width: 33rpx;
						margin-bottom: 15rpx;
					}
					.text {
						width: 100%;
						font-size: 36rpx;
						color: #d4bf97;
						font-weight: 500;
					}
				}
			}
			.baozi {
				width: 310rpx;
				position: absolute;
				bottom: 10rpx;
				left: 289rpx;
				z-index: 1;
			}
			.timer-count {
				width: 590rpx;
				position: absolute;
				bottom: 146rpx;
				left: 100rpx;
				pointer-events: none;
			}
		}
	}
	.gift-content {
		position: absolute;
		top: 350rpx;
		left: 150rpx;
		.gift {
			display: flex;
			justify-content: center;
			align-items: center;
			flex-flow: column;
		}
		.gift1 {
			.bg {
				width: 500rpx;
			}
			.gift-pic {
				width: 500rpx;
				z-index: 2;
			}
			.btn-to-get {
				width: 278rpx;
				z-index: 2;
			}
			.btn-to-gift {
				margin-top: 30rpx;
				width: 278rpx;
				z-index: 2;
			}
		}
		.gift2 {
			.bg {
				width: 500rpx;
			}
			.btn-again {
				margin-top: 60rpx;
				width: 278rpx;
				z-index: 2;
			}
			.gif-emjoy {
				width: 135rpx;
				border-radius: 50%;
				position: absolute;
				top: 35rpx;
			}
		}
		.gift3 {
			.bg {
				width: 500rpx;
			}
			.btn-again {
				margin-top: 60rpx;
				width: 278rpx;
				z-index: 2;
			}
			.btn-to-gift {
				margin-top: 30rpx;
				width: 278rpx;
				z-index: 2;
			}
			.youhuiquan {
				width: 400rpx;
				position: absolute;
				top: 203rpx;
				left: 60rpx;
			}
		}
		.gift4 {
			position: relative;
			.bg {
				width: 500rpx;
				z-index: 2;
			}
			.btn-again {
				margin-top: 60rpx;
				width: 278rpx;
				z-index: 2;
			}
			.user-info {
				z-index: 3;
				.form-name {
					outline: none;
					border: none;
				}
			}
		}
		.mobile-sq {
			position: relative;
			top: 150rpx;
			left: -88rpx;
			.bg {
				width: 622rpx;
			}  
			.txt {
				position: absolute;
				top: 232rpx;
				left: 217rpx;
				width: 300rpx;
				height: 39rpx;
				line-height: 39rpx;
				text-align: left;
				font-size: 24rpx;
				color: #d4bf97;
				font-weight: 500;
			}
			.mobile {
				outline: none;
				border: none;
			  width: 300rpx;
				height: 39rpx;
				position: absolute;
				top: 228rpx;
				left: 217rpx;
				background-color: transparent;
				border-radius: 0;
				opacity: 0;
				&::after {
					border: none;
				}
			}
			.confirm-btn {
				width: 267rpx;
				height: 70rpx;
				position: absolute;
				top: 356rpx;
				left: 185rpx;
			}
		}
		.share-bg {
			.bg {
				width: 500rpx;
			}
			.btn-share2 {
				width: 278rpx;
				height: 80rpx;
				background-color: transparent;
				border-radius: 0;
				background: url('/static/common/image/btn-share2.png') no-repeat center center;
				background-size: 100%;
				margin-top: 50rpx;
				&::after {
					border: none;
				}
			}
			.btn-to-gift {
				width: 278rpx;
				margin-top: 40rpx;
			}
		}
	}
	@keyframes dropDown
	{
		0%{
			-webkit-transform:translateY(0);
			opacity: 1;
		}
		50%{
			-webkit-transform:translateY(600rpx);
			opacity: 1;
		}
		100%{
			-webkit-transform:translateY(1200rpx);
			opacity: 0;
		}
	}
}
::v-deep {
	input {
		font-size: 24rpx!important;
		color: #d4bf97;
		font-weight: 500;
	}
	textarea {
		font-size: 24rpx!important;
		color: #d4bf97;
		font-weight: 500;
		line-height: 1.5;
	}
	.form-username {
		.u-field {
			width: 330rpx;
			position: absolute;
			top: 119rpx;
			left: 100rpx;
		}
	}
	.form-address {
		.u-field {
			width: 460rpx;
			position: absolute;
			top: 300rpx;
			left: 30rpx;
		}
	}
	.form-mobile {
		.u-field {
			width: 330rpx;
			position: absolute;
			top: 186rpx;
			left: 100rpx;
		}
	}
}
</style>
